package com.wh.wisdomsite.xbox.utils.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 采用HttpClient连接服务器进行数据通讯
 * @Package com.wh.wisdomsite.xbox.utils.server
 * @author 谢泽鹏
 * @date 2014年10月14日 下午2:10:42
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
@SuppressWarnings("deprecation")
public class connToserver_HttpClient {


    private static final Log logger = LogFactory.getLog(connToserver_HttpClient.class);

	//声明HttpClient对象
	private static HttpClient httpClient;
	
	//声明httpClient_URL单例对象
	private static connToserver_HttpClient connToserver_httpClient;
	
	//默认请求参数
	private static HttpParams httpParams;

	//获取单例对象
	public static connToserver_HttpClient getInstance() {
		if (connToserver_httpClient == null) {
			connToserver_httpClient = new connToserver_HttpClient();
		}
		return connToserver_httpClient;
	}


	
	/**
	 * 发送POST请求信息
	 * @param url  请求url地址
	 * @param map  请求参数map
	 * @return String   响应结果数据
	 */
	@SuppressWarnings("static-access")
	public String sendPostRequest(String url, Map<String, String> map) {
        //声明result响应结果
        String result = null;
        //服务器响应
        HttpResponse httpResponse = null;
        //请求对象
        HttpPost httpPost = null;
        try {
            //获取httpClient对象
            httpClient = connToserver_httpClient.getSaveHttpClient();
            logger.info("请求参数信息：" + map);
            logger.info("请求URL地址：" + url);
            //构建参数对象
            List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
            //创建HttpPost对象
            httpPost = new HttpPost(url);
            //组装参数集合
            if (null != map && !map.isEmpty()) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            //生成验证参数
            HttpEntity entity = new UrlEncodedFormEntity(paramsList, HTTP.UTF_8);
            //设置entity报文信息
            httpPost.setEntity(entity);
            //发送报文
            httpResponse = httpClient.execute(httpPost);
            //判断请求状态
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //获取响应数据
                result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("请求通信[" + url + "]异常,堆栈信息如下: " + e.getMessage());
            result = null;
        }  catch(ClientProtocolException e){
            e.printStackTrace();
            logger.error("请求通信[" + url + "]异常,堆栈信息如下: " + e.getMessage());
            result = null;
        } catch(IOException e){
            e.printStackTrace();
            logger.error("请求通信[" + url + "]异常,堆栈信息如下: " + e.getMessage());
            result = null;
        } catch(Exception e){
            e.printStackTrace();
            logger.error("请求通信[" + url + "]异常,堆栈信息如下: " + e.getMessage());
            result = null;
        } finally {
            try{
                if(null != httpResponse){
                    httpResponse.getEntity().getContent().close();
                }
                if(null != httpPost){
                    httpPost.getEntity().getContent().close();
                }
            } catch (IllegalStateException e){
                e.printStackTrace();
                logger.error("请求通信[" + url + "]异常,资源清理: " + e.getMessage());
            } catch (IOException e){
                e.printStackTrace();
                logger.error("请求通信[" + url + "]异常,资源清理: " + e.getMessage());
            }
        }
            return result;
	}
	



	/**
	 * 获取http连接客户端
	 * @return
	 */
	public static synchronized HttpClient getSaveHttpClient() {
		if (null == httpParams) {
			httpParams = new BasicHttpParams();
			//设置UserAgent请求协议
			HttpProtocolParams.setUserAgent(httpParams, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Mozilla/5.0(Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			//设置请求协议版本号V1.1
			HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
			//设置字符编码为ISO-8859-1
			HttpProtocolParams.setContentCharset(httpParams, HTTP.DEFAULT_CONTENT_CHARSET);
			//设置请求异常重复请求（服务器是否允许接受请求情景）
			HttpProtocolParams.setUseExpectContinue(httpParams, true);
            //设置重定向，缺省为true
            HttpClientParams.setRedirecting(httpParams, true);

            //设置最大链接数(800链接数)
            ConnManagerParams.setMaxTotalConnections(httpParams, connToserver_Setting.MAX_TOTAL_CONNECTIONS);
            //设置每个路由最大连接数(400个路由)
            ConnPerRouteBean connPerRouteBean = new ConnPerRouteBean(connToserver_Setting.MAX_ROUTE_CONNECTIONS);
            ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRouteBean);
			//设置获取连接的最大等待时间(30秒)
			ConnManagerParams.setTimeout(httpParams, connToserver_Setting.WAIT_TIMEOUT);
			//设置链接超时时长(6秒)
			HttpConnectionParams.setConnectionTimeout(httpParams, connToserver_Setting.CONNECTION_TIMEOUT);
			//设置socket读取数据流超时长(10秒)
			HttpConnectionParams.setSoTimeout(httpParams, connToserver_Setting.READ_TIMEOUT);
			//设置读取数据流缓冲区大小(1024 * 8)
			HttpConnectionParams.setSocketBufferSize(httpParams, connToserver_Setting.BUFFERSIZE);

			//设置我们的HttpClient支持HTTP和HTTPS两种模式
	        SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

	        //使用线程安全的连接管理来创建HttpClient
	        ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
	        httpClient = new DefaultHttpClient(clientConnectionManager, httpParams);
		}
			return httpClient;		
	}

	
	
	
	
	/**
	 * 停止服务
	 */
	@SuppressWarnings("unused")
	private void shutdownHttpClient(){
		  if(httpClient != null && httpClient.getConnectionManager() != null){
		    	httpClient.getConnectionManager().shutdown();
		  }
	}
	  
	  
	  
	 
	/**
	 * 获取链接
	 * @return
	 */
	public HttpClient getHttpClient(){
		    return httpClient;
	 }
	
}
